package com.gewu.pm.app;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.OnHttpListener;
import com.gewu.pm.action.TitleBarAction;
import com.gewu.pm.action.ToastAction;
import com.gewu.pm.http.model.HttpData;
import com.gewu.pm.ui.dialog.WaitDialog;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.widget.broccoli.PlaceholderHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.samlss.broccoli.Broccoli;
import okhttp3.Call;

/**
 *  业务 Activity 基类
 */
public abstract class AppActivity extends BaseActivity
        implements ToastAction, TitleBarAction, OnHttpListener<Object> {

    /** 标题栏对象 */
    private TitleBar mTitleBar;
    /** 状态栏沉浸 */
    private ImmersionBar mImmersionBar;

    /** 加载对话框 */
    private BaseDialog mDialog;
    /** 对话框数量 */
    private int mDialogTotal;
    /** view的预加载占位 */
    Broccoli mBroccoli = new Broccoli();
    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        return mDialog != null && mDialog.isShowing();
    }

    /**
     * 显示加载对话框
     */
    public void showDialog() {
        mDialogTotal++;
        postDelayed(() -> {
            if (mDialogTotal <= 0 || isFinishing() || isDestroyed()) {
                return;
            }

            if (mDialog == null) {
                mDialog = new WaitDialog.Builder(this)
                        .setCancelable(false)
                        .create();
            }
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }, 300);
    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (mDialogTotal > 0) {
            mDialogTotal--;
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog.isShowing() && !isFinishing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void initLayout() {
        super.initLayout();
        //EventBus 默认不注册，子类重写
        if (isRegisteredEventBus()) {
            //注册
            EventBusUtil.register(this);
        }
        if (getTitleBar() != null) {
            getTitleBar().setOnTitleBarListener(this);
        }

        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init();

            // 设置标题栏沉浸
            if (getTitleBar() != null) {
                ImmersionBar.setTitleBar(this, getTitleBar());
            }
        }
        if (mBroccoli ==null){
            mBroccoli = new Broccoli();
        }
    }

    /**
     * 是否使用沉浸式状态栏
     */
    protected boolean isStatusBarEnabled() {
        return true;
    }

    /**
     * 状态栏字体深色模式
     */
    protected boolean isStatusBarDarkFont() {
        return true;
    }

    /**
     * 获取状态栏沉浸的配置对象
     */
    @NonNull
    public ImmersionBar getStatusBarConfig() {
        if (mImmersionBar == null) {
            mImmersionBar = createStatusBarConfig();
        }
        return mImmersionBar;
    }

    /**
     * 初始化沉浸式状态栏
     */
    @NonNull
    protected ImmersionBar createStatusBarConfig() {
        return ImmersionBar.with(this)
                // 默认状态栏字体颜色为黑色
                .statusBarDarkFont(isStatusBarDarkFont())
                // 指定导航栏背景颜色
                .navigationBarColor(android.R.color.white)
                // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
                .autoDarkModeEnable(true, 0.2f);
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (getTitleBar() != null) {
            getTitleBar().setTitle(title);
        }
    }

    @Override
    @Nullable
    public TitleBar getTitleBar() {
        if (mTitleBar == null) {
            mTitleBar = obtainTitleBar(getContentView());
        }
        return mTitleBar;
    }

    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        //overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);//界面切换的动画，感觉会造成卡顿
    }

    @Override
    public void finish() {
        super.finish();
        //overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);//界面切换的动画，感觉会造成卡顿
    }

    /**
     * {@link OnHttpListener}
     */

    @Override
    public void onHttpStart(@NonNull IRequestApi api) {
        //showDialog();
    }

    @Override
    public void onHttpSuccess(Object result) {
        if (result instanceof HttpData) {
            //toast(((HttpData<?>) result).getMessage());
        }
    }

    @Override
    public void onHttpFail(@NonNull Throwable e) {
        toast(e.getMessage());
    }

    @Override
    public void onHttpEnd(@NonNull IRequestApi api) {
        hideDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isShowDialog()) {
            hideDialog();
        }
        mDialog = null;
        //EventBus 默认不注册，子类重写
        if (isRegisteredEventBus()) {
            //反注册
            EventBusUtil.unregister(this);
        }
        if (mBroccoli!=null){
            mBroccoli.clearAllPlaceholders();
            mBroccoli = null;
        }
        // 释放 ImmersionBar 资源，避免 DisplayManager 泄漏
        // ImmersionBar 会在 Activity 销毁时自动清理 DisplayManager 监听器
        // 这里只需要清空引用即可
        mImmersionBar = null;
        // 清空 TitleBar 引用
        mTitleBar = null;
    }

    /**
     * 可以在子类中重写onStickyEventBusCome（）
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(EventBean event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    /**
     * 可以在子类中重写onStickyEventBusCome（）
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onStickyEventBusCome(EventBean event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(EventBean event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(EventBean event) {

    }


    /**
     * 是否注册事件分发
     * <p>
     * 可以在子类中重写isRegisterEventBus（）
     *
     * @return true 注册；false 不注册，默认不注册
     */
    protected boolean isRegisteredEventBus() {
        return false;
    }
    /**
     * 加载前占位布局
     */
    protected void initBroccoli(@IdRes int... ids) {
        for (int id : ids) {
            mBroccoli.addPlaceholders(PlaceholderHelper.getParameter(findViewById(id)));
        }
        mBroccoli.show();
    }
    /**
     * 加载前占位布局
     */
    protected void initBroccoli(View... views){
        for (View view : views) {
            mBroccoli.addPlaceholders(PlaceholderHelper.getParameter(view));
        }
        mBroccoli.show();
    }
    /**
     * 结束加载前占位布局
     */
    protected void endBroccoli(){
        postDelayed(() -> {
            if (mBroccoli!=null) {
                mBroccoli.clearAllPlaceholders();
            }
        }, 0);
    }
}